const express = require('express')
const router = express.Router()
const db = require('../01-封装函数db')
const multer = require('multer')
const upload = multer({ dest: 'uploads/' })
const moment = require('moment');

//分页获取文章接口
router.get('/list', (req, res) => {
    // 设置变量，接收请求参数
    let { pagenum, pagesize, cate_id, state } = req.query;
    // console.log(cate_id, state);
    // 根据cate_id 和 state制作SQL语句的条件
    let w = '';
    if (cate_id) {
        w += ` and cate_id=${cate_id} `;
    }
    if (state) {
        w += ` and state='${state}' `;
    }
    // 分页查询数据的SQL（该SQL用到了连表查询，并且使用了很多变量组合）
    let sql1 = `select a.id, a.title, a.state, a.pub_date, c.name cate_name from article a
    join category c on a.cate_id=c.id
    where author_id=${req.user.id} and is_delete=0 ${w}
    limit ${(pagenum - 1) * pagesize}, ${pagesize}`;
    // 查询总记录数的SQL，查询条件和前面查询数据的条件 必须要一致
    let sql2 = `select count(*) total from article a
    join category c on a.cate_id=c.id
    where author_id=${req.user.id} and is_delete=0 ${w}`;
    // 分别执行两条SQL（因为db查询数据库是异步方法，必须嵌套查询）
    db.db(sql1, (err, result1) => {
        if (err) throw err;
        db.db(sql2, (e, result2) => {
            if (e) throw e;
            res.send({
                status: 0,
                message: '获取文章列表数据成功',
                data: result1,
                total: result2[0].total
            });
        })
    })
});

//添加文章接口
router.post('/add', upload.single('cover_img'), (req, res) => {
    // req.body 表示文本信息
    // req.file 表示上传的文件信息
    // console.log(req.file); // req.file.filename 表示上传之后的文件名

    // 把数据添加到数据表中存起来
    // req.body = { title: 'xx', content: 'xx', cate_id: 1, state: 'xx' }
    let { title, content, cate_id, state } = req.body;
    // 其他字段
    let pub_date = moment().format('YYYY-MM-DD HH:mm:ss');
    let cover_img = req.file.filename;
    let author_id = req.user.id;
    // console.log(obj);
    // return;
    let sql = `insert into article set title='${title}', content='${content}', cate_id=${cate_id}, state='${state}', pub_date='${pub_date}', cover_img='${cover_img}', author_id=${author_id}`;
    db.db(sql, (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '发布成功' })
        } else {
            res.send({ status: 1, message: '发布失败' })
        }
    })
});

//删除文章接口
router.get('/delete/:id', (req, res) => {
    // console.log(req.params);
    let id = req.params.id
    let author_id = req.user.id
    db.db(`update article set  is_delete=1 where id='${id}' and author_id='${author_id}'`, (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '删除成功' })
        } else {
            res.send({ status: 1, message: '删除失败' })
        }
    })
})

//修改文章接口
router.post('/update', upload.single('cover_img'), (req, res) => {
    let { title, cate_id, state, content, id } = req.body
    let cover_img = req.file.filename
    db.db(`update article set title='${title}', cate_id='${cate_id}',state='${state}',content='${content}' where id='${id}'`, (err, result) => {
        if (err) throw err
        if (result.affectedRows > 0) {
            res.send({ status: 0, message: '修改成功' })
        } else {
            res.send({ status: 1, message: '修改失败' })
        }
    })
})

//获取一篇文章接口
router.get('/:id', (req, res) => {
    let id = req.params.id
    db.db(`select * from article where id='${id}'`, (err, result) => {
        if (err) throw err
        res.send({ status: 0, message: '获取成功', data: result[0] })
    })
})

module.exports = router